﻿using System;
using System.Data;
using System.Data.SQLite;

namespace log
{
    class SQLiteHelper
    {
        
        public SQLiteHelper(string db_name,string db_pass="")
        {
            if (db_pass.Length == 0)
            {
                ConnectionString = "Data Source=" + db_name + ";Version=3;";
            }
            else
            {
                ConnectionString = "Data Source=" + db_name + ";Version=3;Password=" + db_pass + ";";
            }
        }

        public void init(string dbname)
        {
            create(dbname);
            string init_sql = "";
            execute(init_sql);

        }

        public void create(string dbname)
        {
            SQLiteConnection.CreateFile(dbname);

        }

        public static string ConnectionString ;


        public DataTable GetData(string sql)
        {


            SQLiteConnection connection = new SQLiteConnection(ConnectionString);


            SQLiteCommand command = new SQLiteCommand(sql, connection);

            SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
            DataTable data = new DataTable();
            try { adapter.Fill(data); }
            catch (Exception) { throw; }
            return data;

        }

        public void execute(string sql)
        {

            if (sql.Length == 0)
            {
                return;
            }
            SQLiteConnection connection = new SQLiteConnection(ConnectionString);


            SQLiteCommand command = new SQLiteCommand(sql, connection);

            connection.Open();

            command.ExecuteNonQuery();

            connection.Close();


        }

        public int insert(string sql)
        {


            SQLiteConnection connection = new SQLiteConnection(ConnectionString);


            SQLiteCommand command = new SQLiteCommand(sql, connection);

            connection.Open();

            command.ExecuteNonQuery();


            command = new SQLiteCommand("select last_insert_rowid() as 'id'", connection);

            int id = Convert.ToInt32(command.ExecuteScalar());

            connection.Close();

            return id;

        }





    }
}
